// pages/rank/index.js

const {
  cityScore,
  cityScoreYear,
  categorys,
  level,
  history
} = require('../../../api/api')
// const util = require('../../../utils/util')
const {
  debounce,checkLogin
} = require('../../../utils/util')

import * as echarts from '../../../components/ec-canvas/echarts.min';
var Chart = null;
const selectorRouteDatas = [{
    id: 0,
    title: "",
    type: "radiobox",
    key: "province",
    items: []
  },
  {
    id: 1,
    title: "2022",
    key: "year",
    type: "radiobox",
    items: []
  },
  {
    id: 2,
    title: "历史",
    key: "category",
    type: "radiobox",
    items: []
  },
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    currentRegion: {},
    data: [],
    datas: [],
    searchlist: [],
    year: 0,
    score: null,
    count: 0,
    yearArr: [],
    section: 0,
    evenNum: 0,
    category: {},
    categoryArr: [],
    selectorList: selectorRouteDatas,
    list: [],
    ec: {
      onInit: function (canvas, width, height, dpr) {
        Chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(Chart);
        return Chart;
      }
    },

    setting: {
      color: '#333333',
      weight: '600',
      fontSize: '30rpx',
      height: '110rpx'
    },
    selectedData: {
      province: 0,
      year: 2022,
      category: '历史'
    },
    routeDistance: 1,
    filterRouteKey: 'batchFilters',
    reverseList: [], //倒叙list

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {
      selectedData,
      selectorList,
      filterRouteKey,
    } = this.data
    selectedData.province = wx.getStorageSync('userCitys').code
    selectorList[0].title = wx.getStorageSync('userCitys').name
    this.setData({
      currentRegion: wx.getStorageSync('userCitys'),
      selectedData,
      selectorList,
    })
    wx.setStorageSync(filterRouteKey, selectedData)
    this.setData({
      mainScore: wx.getStorageSync('score') || '',
      count:wx.getStorageSync('ranking'),
      section:wx.getStorageSync('score')
    })
    this.getYears()
    this.fetchCity()

  },
  updateScore(){
    this.onLoad()
  },
  onShow: function () {
    checkLogin().then((res) => {
      if (!wx.getStorageSync('subjectInfo')) {
        this.setData({
          show: true
        })
      }
    })
  },
  inputChange(e) {
    this.setData({
      score: e.detail.value
    })
  },
  search() {
    let {
      list,
      score,
    } = this.data
    const a=Object.assign({},list[list.length-1],{dataIndex:list.length-1})
    let mainList =[a]
    list.map((item, index) => {
      if (item.score == score) {
        let obj=Object.assign({}, item, {
          dataIndex: index
        })
        mainList=[obj]
      }
    })
      this.callBack(mainList)
  },
  // 获取类别年份
  async getYears() {
    const {
      selectedData,
      filterRouteKey,
      selectorList
    } = this.data
    const {
      result
    } = await categorys(selectedData.province)
    result.sort((a, b) => {
      return b.year - a.year
    }) //倒序
    result.map((item) => {
      item.list.map((e, i) => {
        let obj = {
          id: e,
          title: e
        }
        item.list[i] = obj
      })
    })
    var yearArr = result.map((item) => {
      return {
        id: item.year,
        title: item.year
      }
    })
    if (result.length < 1) {
      return
    }
    const {
      list
    } = result[0]
    selectedData.year = yearArr[0].id
    selectedData.category = list[0].id
    selectorList[1].items = yearArr
    // selectorList[1].title = yearArr[0].title
    selectorList[2].items = list
    this.setData({
      selectorList,
      selectedData
    })
    selectorList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
    })
    this.setData({
      selectorList,
      selectedData
    })
    wx.setStorageSync(filterRouteKey, selectedData)
    this.getBatch()
    // this.getList()
    var category = list[0]
    this.setData({
      data: result,
      year: yearArr[0].title,
      yearArr: yearArr,
      category: category,
      categoryArr: result[0].list,
    })
  },
  async getBatch() {
    const {
      selectedData,
      filterRouteKey,
      selectorList
    } = this.data
    const {
      result
    } = await level(selectedData.province)
    result.sort((a, b) => {
      return b.year - a.year
    }) //倒序
    result.map((item) => {
      item.list.map((e, i) => {
        let obj = {
          id: e,
          title: e
        }
        item.list[i] = obj
      })
    })
    if (result.length < 1) {
      if (selectorList.length > 3) {
        selectorList.pop();
        selectedData.level = ''
        wx.setStorageSync(filterRouteKey, selectedData)
        this.setData({
          datas: [],
          selectorList,
          selectedData
        })
      }
      this.getList()
      return
    }
    const {
      list
    } = result[0]

    // selectedData.year = yearArr[0].id
    selectedData.level = list[0].id
    // selectorList[1].items = yearArr
    // // selectorList[1].title = yearArr[0].title
    selectorList[3] = {
      id: 3,
      title: "",
      key: "level",
      type: "radiobox",
      items: list
    }
    //  selectorList[3].items = list
    this.setData({
      selectorList,
      selectedData
    })
    selectorList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
    })
    this.setData({
      selectorList,
      selectedData
    })
    wx.setStorageSync(filterRouteKey, selectedData)
    this.setData({
      datas: result,
    })
    this.getList()

  },
  async fetchCity() {
    const {
      type,
      selectorList
    } = this.data
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    selectorList[0].items = cityList
    this.setData({
      selectorList
    })

  },
  filterKeyFunc() {
    const {
      filterRouteKey
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)
    const {
      selectorList,
      data,
      datas
    } = this.data
    if (selectedData['province'] !== this.data.selectedData['province']) {
      this.setData({
        selectedData
      })
      wx.setStorageSync(filterRouteKey, selectedData)
      this.getYears()
      return
    }
    var list = []
    data.map((item) => {
      if (item.year == selectedData['year']) {
        list = item.list
        if (selectedData['year'] !== this.data.selectedData['year']) {
          selectedData['category'] = list[0].id
          wx.setStorageSync(filterRouteKey, selectedData)
        }
      }
    })

    const newDatas = datas.filter(e => {
      return e.year == selectedData['year']
    })
    if (newDatas.length <= 0) {
      selectedData['level'] = ''
      if (selectorList.length > 3) {
        selectorList.pop()
      }
    } else {
      selectorList[3] = {
        id: 3,
        title: newDatas[0].list[0].id,
        key: "level",
        type: "radiobox",
        items: newDatas[0].list
      }
      if (selectedData['level'] === this.data.selectedData['level']) {
        selectedData['level'] = newDatas[0].list[0].id
      }
    }
    wx.setStorageSync(filterRouteKey, selectedData)
    selectorList[2].items = list
    selectorList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
    })
    this.setData({
      selectorList,
      selectedData
    })
    this.getList()
  },
  async onSelectChangedRoute(e) {
    const {
      filterRouteKey
    } = this.data
    wx.setStorageSync(filterRouteKey, {
      ...e.detail
    });
    this.filterKeyFunc()
  },

  setEcharts(scoreData, numData) {
    var that = this
    var option = {
      grid: {
        top: 38,
        right: 30,
        bottom: 48,
        left: 63,
      },
      color: ['#FBA300'],
      xAxis: {
        type: 'category',
        data: scoreData,
        // data: [0,150,350,550,750],
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#f2f2f2',
          }
        },
        axisLabel: {
          fontSize: 11,
          color: '#4d4d4d',
          formatter: '{value}分',
          margin: 15,
        },
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        axisTick: {
          show: false
        },
        axisLabel: {
          color: "#4d4d4d", //坐标的字体颜色
          fontSize: 11,
          formatter: '{value}人'
        },
        splitLine: {
          lineStyle: {
            type: 'solid',
            color: '#f2f2f2'
          }
        },
        splitNumber: 4
      },
      tooltip: {
        trigger: 'axis',
        formatter: debounce(function (params) {
          that.callBack(params)
        }, 500),
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: '#FFE67D'
          }
        }
      },
      series: [{
        // data: [0,150,350,550,750],
        data: numData,
        type: 'line',
        showSymbol: false,
        symbol: 'circle',
        symbolSize: 8,
        areaStyle: {
          opacity: 0.5,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(252,206,0,.5)'
            },
            {
              offset: 1,
              color: '#ffffff'
            }
          ])
        },
        lineStyle: {
          normal: {
            width: 1,
            curveness: 0.5,
          }
        },
        emphasis: {
          lineStyle: {
            width: 1,
            curveness: 0.5,

          },
        },
        smooth: 0.6
      }]
    }
    Chart.setOption(option);
    Chart.on('click', function (params) {})
  },
  callBack(params) {
    console.log(params)
    const {
      reverseList
    } = this.data
    const {
      dataIndex
    } = params[0]
    // console.log(dataIndex)
    const res = reverseList[dataIndex]
    const num = res.num
    const res1 = reverseList[dataIndex - 1]
    this.setData({
      evenNum: res.num,
      section: res.score,
      count: res.total - num + '-' + res.total,
    })
    this.getHistory()
  },
// 获取历年等位分
  async getHistory(){
    const {
      section,selectedData
    }=this.data
    const params = {
      year: selectedData.year,
      cityCode: selectedData.province,
      category: selectedData.category,
      level: selectedData.level || '',
      score:section
    }
    const {result}=await history(params)
    this.setData({
      halvingList:result
    })
  },
  //分数端
  getList() {
    wx.showLoading({
      title: '加载中...',
    })
    const {
      selectedData,
      mainScore
    } = this.data
    const params = {
      year: selectedData.year,
      code: selectedData.province,
      category: selectedData.category,
      level: selectedData.level || ''
    }
    this.getHistory()
    cityScore(params).then((res) => {
      const newList = JSON.parse(JSON.stringify(res.result))
      this.setData({
        list: res.result,
        reverseList: newList.reverse(),
        searchlist: res.result,
        score: ''
      })
      const obj=Object.assign({},newList[0],{dataIndex:1})
      let mainList =[]
      newList.map((item, index) => {
        if (item.score == mainScore) {
          let obj=Object.assign({}, item, {
            dataIndex: index
          })
          mainList=[obj]
        }
      })
      if(mainList.length>0){
        this.callBack(mainList)
      }
      const reverseResult = res.result.reverse()
      const list = reverseResult.filter((item) => {
        return item.num > 0
      })
      const scoreData = list.map(e => {
        return e.score
      })
      const numData = list.map(e => {
        return e.num
      })
      this.setEcharts(scoreData, numData)
      wx.hideLoading({})
    }).catch((e) => {})
  },

  top() {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
  },
  onPageScroll: function (e) {
    //控制回到顶部按钮显示+隐藏
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  onReady: function () {
    this.lineComponent = this.selectComponent('#mychart');
  },
  onReachBottom() {},
  goto() {
    wx.navigateTo({
      url: '/pages/school/detail/index',
    })
  },
  onShareAppMessage(){
    return {
      title: '一分一段',
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }
})
